package weather.app.pack;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.ListActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Toast;

public class ActivityThree extends ListActivity{
	
	HashMap<String,String> xmlDataA = new HashMap<String,String>();
	Document xml;
	
	public void onCreate(Bundle savedInstanceState) 
	{

		super.onCreate(savedInstanceState);
		setContentView (R.layout.second);
       
		//catch accidental disk or network access on the app's main thread, 
		//where UI operations are received and animations take place
    	StrictMode.enableDefaults();
    	
     
    	// get the name of the city
		Bundle extras = getIntent().getExtras();
		
        if(extras != null) 
        {
        	
        	String city = extras.getString("city");
            
            String adresa_url_vreme_oras = "http://www.google.com/ig/api?weather="+city;
            try 
            {
            	
            	HttpGet getMethod=new HttpGet(adresa_url_vreme_oras);
            	HttpClient client = new DefaultHttpClient ();
          
            	ResponseHandler<String> responseHandler=new BasicResponseHandler();
            	// responseBody - content of the retrieved RSS file
      			String responseBody=client.execute(getMethod, responseHandler);
      			      			      			
      			xml = XMLfromString(responseBody);
      			
      			
      		}
            catch (Throwable t) 
            {
      		
            	t.printStackTrace();
      		}
            
            //parsing xml file
            xmlDataA = parseXML(xml);
            
            //dialog.dismiss();
            List<String> values = new ArrayList<String>();
 			 // Get a set of the entries
			Set<Entry<String, String>> set = xmlDataA.entrySet();
			// Get an iterator
			Iterator<Entry<String, String>> i = set.iterator();
		
			// Add elements to the list of values
			while(i.hasNext()) 
			{
				Map.Entry<String, String> me = (Map.Entry<String, String>)i.next();
				
				values.add(me.getKey() +me.getValue());
				
			}
			
			//sort
			Collections.sort(values);	
			
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, values);
			
			setListAdapter(adapter);
            
        }
      
        //Done button
        final Button button = (Button) findViewById(R.id.button);
        /**
         * OnClickListener
         */
        button.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View v) 
            {
            	
                // Perform action on clicks
                Toast.makeText(ActivityThree.this, "Done button clicked", Toast.LENGTH_SHORT).show();
                
            	finish();
            }
        });// end OnClickListener
 
    }
	
	/**
	 * 
	 * @param xml
	 * @return
	 */
	
	private HashMap<String,String> parseXML(Document xml) {
		HashMap<String,String> xmlData = new HashMap<String,String>();
		List<String> tag = new ArrayList<String>();
		
		tag.add("forecast_information");
		tag.add("current_conditions");
		tag.add("forecast_conditions");
		tag.add("problem_cause");
		
		int ik = 0;
		int iki=5;
		
		for(int t=0;t<tag.size();t++)
		{
			
			NodeList nodes = xml.getElementsByTagName(tag.get(t));
			
			for(int i =0;i<nodes.getLength();i++){
				
				if(tag.get(t).equals("forecast_conditions")){
					ik = 0;
					iki++;
				}
				
				else if(tag.get(t).equals("problem_cause")){
					xmlData.put("There is no forecast available for the city you've chosen: ", "Press Done to chose another city");
					//Toast.makeText(this, "There is no forecast available for the city you've choosen",Toast.LENGTH_SHORT).show();
				}
				
				for(int j=0;j<nodes.item(i).getChildNodes().getLength();j++){
					
					Node n = nodes.item(i).getChildNodes().item(j);
				
					String nodeName = n.getNodeName();
					
					if(nodeName.equals("city")){
						
						xmlData.put("0) City:",n.getAttributes().item(0).getNodeValue());
						
					}
					
					else if(nodeName.equals("forecast_date")){
						
						xmlData.put("1) Date:",n.getAttributes().item(0).getNodeValue());
						
					}
					
					else if(nodeName.equals("condition") && tag.get(t).equals("current_conditions")){
						xmlData.put("2) Current Conditions:",n.getAttributes().item(0).getNodeValue());
					
					}
					
					else if (nodeName.equals("temp_c")){
						xmlData.put("3) Temp Celsium:",n.getAttributes().item(0).getNodeValue());
						
					}
					
					else if (nodeName.equals("humidity")){
						xmlData.put("4) :",n.getAttributes().item(0).getNodeValue());
						
					}
					
					else if (nodeName.equals("wind_condition")){
						xmlData.put("5) ",n.getAttributes().item(0).getNodeValue());
						
					}
					
					else if (nodeName.equals("day_of_week")){
						
						xmlData.put(iki+"."+ik+")"+" Day of the week:",n.getAttributes().item(0).getNodeValue());
						ik++;
					}
					
					else if (nodeName.equals("low")){
						
						xmlData.put(iki+"."+ik+")"+" Low temp celsium:",n.getAttributes().item(0).getNodeValue());
						ik++;
					}
					
					else if (nodeName.equals("condition")&& tag.get(t).equals("forecast_conditions")){
						
						xmlData.put(iki+"."+ik+")"+" F conditions:",n.getAttributes().item(0).getNodeValue());
						
					}	
					
				}// end for j 'arg'
				
				
			}// end for i
			
		}// end for t 'TAG'
		return xmlData;
		

	}
	
	/**
	 * 
	 * @param xml
	 * @return
	 */
	public Document XMLfromString(String xml){
		 
	    Document doc = null;
	 
	    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	        try {
	 
	        DocumentBuilder db = dbf.newDocumentBuilder();
	 
	        InputSource is = new InputSource();
	            is.setCharacterStream(new StringReader(xml));
	            doc = db.parse(is);
	 
	        } catch (ParserConfigurationException e) {
	            System.out.println("XML parse error: " + e.getMessage());
	            return null;
	        } catch (SAXException e) {
	            System.out.println("Wrong XML file structure: " + e.getMessage());
	            return null;
	        } catch (IOException e) {
	            System.out.println("I/O exeption: " + e.getMessage());
	            return null;
	        }
	 
	        return doc;
	 
	    }
	

}
